<template>
    <el-drawer
        v-model="drawerShow"
        title="会话窗口"
        size="280px"
        @close="emits('close')"
    >
        <div class="sessions-widgets">
            <div class="header">
                <div class="flex items-center">
                    <el-button class="flex flex-1 items-center h-10" @click="handleSessionCreate">
                        <span class="text-xl">+</span>
                        <span class="ml-1.5">新建会话</span>
                    </el-button>
                    <el-button class="p-6 h-10" @click="handleSessionClare">
                        <icon name="el-icon-DeleteFilled" size="20"/>
                    </el-button>
                </div>
                <div class="pt-2.5">
                    <el-input
                        v-model="searchKeyword"
                        class="h-2"
                        placeholder="搜索对话"
                        :prefix-icon="Search"
                        @input="handleInputChange"
                    />
                </div>
            </div>
            <el-scrollbar class="flex-1 min-h-0">
                <div
                    v-for="(item, index) in sessionList"
                    :key="index"
                    class="session-item"
                    :class="sessionId === item.id ? 'active' : ''"
                    @click="handleChangeItem(item.id, item.name)"
                >
                    <icon name="el-icon-ChatLineRound" size="16"/>
                    <div class="flex-1 mx-2">
                        <el-input v-if="editIndex === index" v-model="inputName" size="small" />
                        <span v-else class="line-clamp-1 h-[24px]">{{ item.name }}</span>
                    </div>

                    <template v-if="sessionId === item.id">
                        <div v-if="editIndex !== index" class="flex items-center">
                            <div class="cursor-pointer h-[18px] mr-[6px]" @click.stop="handleChangeInputs(index)">
                                <icon name="el-icon-Edit" />
                            </div>
                            <div class="cursor-pointer h-[18px]">
                                <el-popconfirm
                                    width="150"
                                    :hide-icon="false"
                                    :icon="InfoFilled"
                                    icon-color="#626AEF"
                                    confirm-button-text="删除"
                                    cancel-button-text="取消"
                                    title="确定要删除?"
                                    @confirm="handleSessionDelete(item.id)"
                                >
                                    <template #reference>
                                        <icon name="el-icon-Delete" />
                                    </template>
                                </el-popconfirm>
                            </div>
                        </div>
                        <div v-else class="flex items-center">
                            <div class="cursor-pointer h-[18px] mr-[6px]">
                                <icon name="el-icon-Select" @click.stop="handleSessionUpdate(item.id)" />
                            </div>
                            <div class="cursor-pointer h-[18px]">
                                <icon name="el-icon-CloseBold" @click.stop="editIndex = -1" />
                            </div>
                        </div>
                    </template>
                </div>
                <div v-if="sessionList.length <= 0">
                    <el-empty description="暂无会话" />
                </div>
            </el-scrollbar>
        </div>
    </el-drawer>
</template>

<script setup lang="ts">
import { throttle } from 'lodash-es'
import { Search, InfoFilled } from '@element-plus/icons-vue'
import chatSessionApi from '~/api/agent/chat/session'
import feedback from '~/utils/feedback'

const emits = defineEmits(['change', 'update', 'close'])
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    bot: {
        type: String,
        default: ''
    },
    sid: {
        type: Number,
        default: 0
    },
    lists: {
        type: Array,
        default: () => {
            return []
        }
    }
})

// 抽屉显示
const drawerShow = ref<boolean>(false)

// 搜关键词
const searchKeyword = ref<string>('')

// 编辑下标
const editIndex = ref<number>(-1)

// 编辑框值
const inputName = ref<string>('')

// 当前会话ID
const sessionId = ref<number>(0)

// 会话窗口列表
const sessionList = ref<ChatSessionListResponse[]>([])

/**
 * 关键词搜索
 *
 * @author zero
 */
const handleInputChange = throttle(async () => {
    emits('update', sessionId.value, searchKeyword.value.trim())
}, 500)

/**
 * 会话窗创建
 *
 * @author zero
 */
const handleSessionCreate = async () => {
    await chatSessionApi.add(props.bot, '新的会话')
    emits('update')
}

/**
 * 会话窗更新
 *
 * @param id
 * @author zero
 */
const handleSessionUpdate = async (id: number) => {
    await chatSessionApi.edit(id, inputName.value)
    emits('update')
    resetEditInput()
}

/**
 * 会话窗删除
 *
 * @param id
 * @author zero
 */
const handleSessionDelete = async (id: number) => {
    await chatSessionApi.delete(id)
    feedback.msgSuccess('删除成功')
    emits('update')
}

/**
 * 会话窗清空
 *
 * @author zero
 */
const handleSessionClare = async () => {
    feedback.confirm('您确定要清空所有会话窗口吗?')
        .then(async () => {
            await chatSessionApi.clear(props.bot)
            feedback.msgSuccess('清空成功')
            emits('update')
        }).catch()
}

/**
 * 会话窗编辑框
 *
 * @param index
 * @author zero
 */
const handleChangeInputs = (index: number) => {
    editIndex.value = index
    inputName.value = sessionList.value[index].name
}

/**
 * 会话窗切换
 *
 * @author zero
 * @param id
 * @param name
 */
const handleChangeItem = (id: number, name: string) => {
    if (id !== sessionId.value) {
        sessionId.value = id
        emits('change', id, name)
        resetEditInput()
    }
}

/**
 * 重置编辑框
 */
const resetEditInput = () => {
    editIndex.value = -1
    inputName.value = ''
}

/**
 * 监听抽屉显示
 */
watch(
    () => props.show,
    async (val) => {
        drawerShow.value = val
        sessionId.value = props.sid
    }
)

/**
 * 监听列表变化
 */
watch(
    () => props.lists,
    () => {
        resetEditInput()
        sessionId.value = props.sid
        sessionList.value = props.lists as ChatSessionListResponse[]
    }
)
</script>

<style scoped lang="scss">
.sessions-widgets {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .header {
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 1px solid var(--el-border-color-light);
    }
    .session-item {
        display: flex;
        align-items: center;
        padding: 8px 14px;
        margin-bottom: 8px;
        color: var(--el-text-color-regular);
        cursor: pointer;
        border-radius: 8px;
        .el-dropdown-link {
            visibility: hidden;
        }
        &.active {
            color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-9);
        }
        &:hover {
            &:not(.active) {
                background-color: var(--el-color-hover);
            }
            .el-dropdown-link {
                visibility: visible;
            }
        }
    }
}
</style>
